package com.whosly.fast.web.quickly.config;

import com.whosly.fast.web.quickly.filter.xss.XssFilter;
import com.whosly.fast.web.quickly.util.StringUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.DispatcherType;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class FilterConfiguration {

    @Resource
    private FilterConfig filterConfig;

    @SuppressWarnings({ "rawtypes", "unchecked" })
    @Bean
    public FilterRegistrationBean xssFilterRegistration()
    {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setDispatcherTypes(DispatcherType.REQUEST);
        registration.setFilter(new XssFilter());

        registration.addUrlPatterns(StringUtils.split(filterConfig.getUrlPatterns(), ","));
        registration.setName("xssFilter");
        registration.setOrder(FilterRegistrationBean.HIGHEST_PRECEDENCE);

        Map<String, String> initParameters = new HashMap<String, String>();
        initParameters.put("excludes", filterConfig.getExcludes());
        registration.setInitParameters(initParameters);

        return registration;
    }

}
